//
//  SEGMyProfileViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/10.
//

#import "SEGMyProfileViewModel.h"
#import "SEGMyManager.h"

@interface SEGMyProfileViewModel ()

/// 请求Manager
@property (nonatomic, strong)SEGMyManager *myManager;

@end

@implementation SEGMyProfileViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self seg_createProfileCommand];
        [self seg_createUploadIconCommand];
        [self seg_createUpdateInfoCommand];
    }
    return self;
}
- (void)seg_createProfileCommand {
    @weakify(self);
    self.profileCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        @strongify(self);
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [self doLogic_myprofile];
            [subscriber sendNext:@""];
            [subscriber sendCompleted];
            return nil;
        }];
    }];
}
- (void)seg_createUploadIconCommand {
    @weakify(self);
    self.uploadIconCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(UIImage *editedImage) {
        @strongify(self);
        if (editedImage.size.width * editedImage.size.height > 102400) { // 是大图片，进行压缩
            self.imageData = [NSData dataWithData:UIImageJPEGRepresentation(editedImage, 0.5)];
        } else { // 小图片，不压缩质量
            self.imageData = [NSData dataWithData:UIImageJPEGRepresentation(editedImage, 1.0)];
        }
        // 显示头像
        UIImage *img = [UIImage imageWithData:self.imageData];
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
               [[SEGOnefileuploadManager sharedManager] requestOnefileuploadWithImage:img progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
                   if (!isSuccessed) {
                       [subscriber sendError:error];
                       return;
                   }
                   NSString *imageStr = [result valueForKey:@"data"];
                   [SEGProfileManager sharedManager].profile.ico = imageStr;
                   // 用户信息保存到本地
                   [SEGProfileManager seg_SaveSystemAccountWithUserID:[SEGProfileManager sharedManager].profile];

                   //存储图片地址 -- 便于后续上传
                   NSString *imagePath = [SEGProfileManager sharedManager].profile.ico;
                   NSString *nickname = (1 < self.seg_segmyprofilelogicmodel.count) ? self.seg_segmyprofilelogicmodel[1].desc : @"";
                   NSString *desc = @"";
                   for (SEGMyProfileLogicModel *object in self.seg_segmyprofilelogicmodel) {
                       if ([object.key isEqualToString:@"5"]) desc = object.desc;
                   }
                   
                   // 更新个人信息
                   [self.myManager requestUpdateProperyInfoBynickname:nickname ico:imagePath name:@"" age:@"" sex:@"" job:@"" desc:desc identity:@"" Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                       // 存储修改之后的数据
                       [SEGProfileManager sharedManager].profile.nickname = nickname;
                       [SEGProfileManager sharedManager].profile.desc = desc;
                       [SEGProfileManager sharedManager].profile.ico = imagePath;
                       [subscriber sendNext:errorMessage];
                       [subscriber sendCompleted];
                   }];
               }];
            
            return nil;
        }];
    }];
}
- (void)seg_createUpdateInfoCommand {
    @weakify(self);
    self.updateInfoCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(RACTuple *tuple) {
        RACTupleUnpack(NSDictionary *userInfo, NSDictionary *dict) = tuple;
        
        NSString *nickname = (1 < self.seg_segmyprofilelogicmodel.count) ? self.seg_segmyprofilelogicmodel[1].desc : @"";
        nickname = [[userInfo valueForKey:@"name"] isEqualToString:@"nickName"] ? [dict valueForKey:@"UITextField"] : nickname;
        
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        nickname = [nickname stringByTrimmingCharactersInSet:set];
        
        NSString* desc = @"";
        for (SEGMyProfileLogicModel *object in self.seg_segmyprofilelogicmodel) {
            if ([object.key isEqualToString:@"5"]) desc = object.desc;
        }
        desc = [[userInfo valueForKey:@"name"] isEqualToString:@"desc"] ? [dict valueForKey:@"UITextView"] : desc;
        NSString *sex = [dict valueForKey:@"UITableView_MaleType"];
        NSString *job = [dict valueForKey:@"UITableView_JobType"];
        NSString *jobName = [dict valueForKey:@"UITableView_JobName"];
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.myManager requestUpdateProperyInfoBynickname:nickname ico:@"" name:@"" age:@"" sex:sex job:job desc:desc identity:@""
            Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    if (sex && sex.length != 0) {
                        [SEGProfileManager sharedManager].profile.sex = sex;
                    }
                    if (job && job.length != 0) {
                         [SEGProfileManager sharedManager].profile.job = job;
                    }
                    if (jobName && jobName.length != 0) {
                        [SEGProfileManager sharedManager].profile.jobName = jobName;
                    }
                    [SEGProfileManager sharedManager].profile.nickname = nickname;
                    [SEGProfileManager sharedManager].profile.desc = desc;
                    
                    [subscriber sendNext:errorMessage];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            
            return nil;
        }];
    }];
}

- (void)doLogic_myprofile {
    NSArray* _dataSourceArr = @[@{@"key":@"1",@"name":@"头像",@"showRightIco":@"1",@"desc":@"修改头像"},
                           @{@"key":@"2",@"name":@"昵称",@"showRightIco":@"1",@"desc":@""},
                           @{@"key":@"4",@"name":@"手机号码",@"showRightIco":@"0",@"desc":@""},
                           @{@"key":@"5",@"name":@"个人描述",@"showRightIco":@"1",@"desc":@""}
                           ];
    
    NSMutableArray* arrM = [NSMutableArray array];
    for (NSDictionary* dict in _dataSourceArr) {
        SEGMyProfileLogicModel* model = [SEGMyProfileLogicModel initWithDictionary:dict];
        switch ([model.key integerValue]) {
            case 1: //修改头像
                model.desc = [SEGProfileManager sharedManager].profile.ico;
                break;
            case 2: //昵称
                model.desc = [SEGProfileManager sharedManager].profile.nickname;
                break;
            case 3: //配送地址
                model.desc = [SEGProfileManager sharedManager].profile.defaultAddress;
                break;
            case 4: //手机号码
                model.desc = [SEGProfileManager sharedManager].profile.tel;
                break;
            case 5: //个人描述
                model.desc = [SEGProfileManager sharedManager].profile.desc;
                break;
            case 6: //积分等级
                model.desc = [SEGProfileManager sharedManager].profile.levelUrl;
                break;
            case 7:{ //性别
                model.desc = [SEGProfileManager sharedManager].profile.sex;
                break;
            }
            case 8: //职业;
                model.desc = [SEGProfileManager sharedManager].profile.jobName;
                break;
            default:
                break;
        }
        [arrM addObject:model];
    }
    
    self.seg_segmyprofilelogicmodel = arrM;
}

#pragma mark - Getter
- (NSArray<SEGMyProfileLogicModel *> *)seg_segmyprofilelogicmodel {
    if (!_seg_segmyprofilelogicmodel) _seg_segmyprofilelogicmodel = [NSArray array];
    return _seg_segmyprofilelogicmodel;
}
- (SEGMyManager *)myManager {
    if (!_myManager) _myManager = [[SEGMyManager alloc] init];
    return _myManager;
}

@end
